package chapter19CountDownLatch;

import java.util.concurrent.CountDownLatch;

/**
 * 主线程等待5个子线程全部完成指定工作后，再继续运行
 * Created by LinGer on 2019/6/26
 */
public class CountDownLatchTest extends Thread {

    private static int LATCH_SIZE = 5;
    private static CountDownLatch doneSignal;

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(this.getName() + " sleep 1s");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //countDown()应该在finally块中调用
            doneSignal.countDown();
        }
    }

    public static void main(String[] args) {
        try{
            //如果countDown()没有等于0，则程序会继续阻塞等待
            doneSignal = new CountDownLatch(LATCH_SIZE);

            for (int i = 0; i < LATCH_SIZE; i++) {
                new CountDownLatchTest().start();
            }

            System.out.println("main begin await");
            doneSignal.await();
            System.out.println("main finish await");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
